package service

import (
	"context"
	"gorm.io/gorm"
	"shop-bean/dto"
	"shop-bean/model"
	"shop-bean/request"
	"shop-common/library/variables"
	"shop-service/repository"
)

type IBasketService interface {
	FindByUserIdShopCart(ctx context.Context, userId string) ([]*dto.ShopCartItemDto, error)
	DeleteBatchByBasketIds(ctx context.Context, userId string, basketIds []uint) error
	DeleteAllShopCart(ctx context.Context, userId string) error
	Create(ctx context.Context, form *request.ChangeShopCartRequest, userId string) error
	Updates(ctx context.Context, basket *model.Basket) error
	UpdateBasketByShopCart(userId string) error
}

type BasketService struct {
	db         *gorm.DB
	repository repository.IBasketRepository
}

func NewBasketService() IBasketService {
	return &BasketService{variables.GormDB(), repository.NewBasketRepository()}
}

func (s *BasketService) FindByUserIdShopCart(ctx context.Context, userId string) ([]*dto.ShopCartItemDto, error) {
	//todo 在这个类里面要调用这里的缓存信息，并没有使用aop，所以不使用注解

	return nil, nil
}

func (s *BasketService) DeleteBatchByBasketIds(ctx context.Context, userId string, basketIds []uint) error {
	err := s.repository.DeleteShopCartItemsByBasketIds(s.db, userId, basketIds)
	if err != nil {
		variables.Logger.Error(ctx, "delete by userId and basketIds failed: err %v", err)
		return err
	}
	return nil
}

func (s *BasketService) DeleteAllShopCart(ctx context.Context, userId string) error {
	err := s.repository.DeleteAllShopCartItems(s.db, userId)
	if err != nil {
		variables.Logger.Error(ctx, "deleteAll by userId failed: err %v", err)
		return err
	}
	return nil
}

func (s *BasketService) Updates(ctx context.Context, basket *model.Basket) error {
	err := s.repository.Updates(s.db, basket)
	if err != nil {
		variables.Logger.Errorf(ctx, "updates basket failed: err %v", err)
		return err
	}
	return nil
}

func (s *BasketService) Create(ctx context.Context, form *request.ChangeShopCartRequest, userId string) error {
	err := s.repository.Create(s.db, &model.Basket{
		ShopId:             form.ShopId,
		ProdId:             form.ProdId,
		SkuId:              0,
		UserId:             userId,
		BasketCount:        form.Count,
		DistributionCardNo: form.DistributionCardNo,
	})

	if err != nil {
		variables.Logger.Errorf(ctx, "create by userId failed: err %v, userId %d", err, userId)
		return err
	}

	return nil
}

func (s *BasketService) UpdateBasketByShopCart(userId string) error {

	return nil
}
